from django.shortcuts import render
from .models import *
from .serializers import *
# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

class clientData(APIView):
    """
    post:
        添加更新数据
        name:客户端名称
        fraction：分数
    get:
        获取排名
        name
    """

    def post(self, request):
        try:
            canshu = request.POST
            # 判断数据格式是否正确
            if canshu['fraction'] > 0 and isinstance(canshu['fraction'], int):
                # 添加获取客户端
                client = Client.objects.get_or_create(name=canshu['name'])
                # 判断是否为当前客户端最高分数
                try:
                    # 获取历史最高分
                    zgf = ClientRanking.objects.get(client=client, highest=True)
                    # 比较历史最高分是否比最新分数高
                    if zgf.fraction > canshu['fraction']:
                        highest = False
                    else:
                        highest = True
                except:
                    # 当没有分数时，当前为最高分
                    highest = True
                # 添加客户端上传分数
                ClientRanking.objects.create(client=client, fraction=int(canshu['fraction']), highest=highest)
                res_data = {'result': 'ok', 'message': '数据更新成功！'}
            else:
                res_data = {'result': 'error', 'message': '数据格式错误！'}
            return Response(res_data, status.HTTP_201_CREATED)
        except:
            res_data={'result': 'error', 'message': '数据更新失败！'}
            return Response(res_data, status.HTTP_400_BAD_REQUEST)



    def get(self, request):
        try:
            canshu = request.GET
            # 获取范围内的数据
            data = ClientRanking.objects.filter(highest=True)[int(canshu['start'])-1:int(canshu['end'])]
            data_list = ClientRankingSerializers(data, many=True).data
            # 添加排名
            data_list = list(map(PaiMing, data_list, range(int(canshu['start'])-1, int(canshu['end']))))
            # 添加调用客户端排名
            user = ClientRanking.objects.get(client__name=canshu['name'], highest=True)
            num = ClientRanking.objects.filter(fraction__gt=user.fraction).count()
            data_list.append({'client': user.name, 'fraction': user.fraction, 'ranking': num+1})
            res_data = {'result': 'ok', 'message': '查询成功！', 'data': data_list}
            return Response(res_data, status.status.HTTP_200_OK)
        except:
            res_data={'result':'error','message': '查询失败！'}
            return Response(res_data,status.HTTP_400_BAD_REQUEST)


def PaiMing(rmp, ll):
    rmp['ranking'] = ll+1
    return rmp